package com.offcn.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.UUID;

/**
 * @Auther: zmb
 * @Date: 2021/12/28 13:54
 * @Description:
 */
public class JwtUtils {

    private static final String SECRET_KEY = "u-member-offcn123"; //秘钥
    public static final long TOKEN_EXPIRE_TIME = 5 * 60 * 1000; //token过期时间
    public static final long REFRESH_TOKEN_EXPIRE_TIME = 10 * 60 * 1000; //refreshToken过期时间
    private static final String ISSUER = "offcn"; //签发人

    //生成令牌
    public static String createJwt(String username) {
        Date date = new Date();
        return Jwts.builder()
                .setId(UUID.randomUUID().toString())
                .setIssuer(ISSUER)
                .setIssuedAt(date)   //创建时间
                .setExpiration(new Date(date.getTime() + TOKEN_EXPIRE_TIME))     //过期时间
                .claim("username", username)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }


    //对令牌验签
    public static boolean verify(String token) {
        try {
            parseToken(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    //解析令牌
    public static Claims parseToken(String token) {
        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();
    }
    //取得用户名称
    public static String getUsername(String token) {
        Claims claims = parseToken(token);
        String username = (String) claims.get("username");
        return username;
    }
}
